package com.teach.util.impl;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import com.teach.CodeException;
import com.teach.config.ConfigProperties;
import com.teach.util.JwtUtil;

import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 * -
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2022-08-23 20:40
 * Version : 1.0
 * Copyright 2022 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 **/
@Component
public class JwtUtilImpl implements JwtUtil {

  private ConfigProperties config;
  private static String KEY = "k";

  public JwtUtilImpl(ConfigProperties config){
    this.config = config;
  }

  /**
   * 创建jwt
   * @param payloads
   * @return
   */
  public String create(Object payloads){
    Map<String,Object> map = new HashMap<>();
    map.put(KEY, payloads);
    return JWT.create().addPayloads(map)
        .setExpiresAt(new Date(System.currentTimeMillis()+config.getJwt().getExpire().toMillis()))
        .setKey(config.getJwt().getKey()).sign();
  }

  public void verify(String jwt){
    if(!cn.hutool.jwt.JWTUtil.verify(jwt, config.getJwt().getKey())){
      throw new CodeException(10,"口令验证未通过");
    }
    try {
      JWTValidator.of(jwt).validateDate();
    }catch (Exception ex){
      throw new CodeException(11,"口令已过期",ex);
    }
  }

  public <T> T parse(String jwt,Class<T> cls){
    return cn.hutool.jwt.JWTUtil.parseToken(jwt).getPayloads().getBean(KEY,cls);
  }
}
